package com.cyz.mobile;


import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyz.service.CouponService;
import com.cyz.service.UserCouponService;
import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.domain.Notify;
import com.demo.domain.UserNotify;
import com.demo.mobile.MobException;
import com.demo.mobile.MobileInfo;
import com.demo.util.DateUtil;
import com.demo.util.StringUtil;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.UserAddress;
import com.shopcart.service.OrderService;
import com.shopcart.service.StoreCommentService;
import com.shopcart.service.StoreGoodsCategoryService;
import com.shopcart.service.UserAddressService;
import com.vsd.domain.UserCollect;
import com.vsd.mobile.error.MEnumError;
import com.vsd.service.NotifyService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StorePhotoService;
import com.vsd.service.StoreService;
import com.vsd.service.UserCollectService;
import com.vsd.service.UserNotifyService;
import com.zy.order.proto.MSOrder.MCouponList;
import com.zy.store.proto.MOAppStore.MMyCommentList;
import com.zy.store.proto.MOAppStore.MStoreMiniList;
import com.zy.store.proto.MOAppStore.MTgGoodsMiniList;
import com.zy.sys.proto.MOCommon.MRet;
import com.zy.user.proto.MOUser.MAddress;
import com.zy.user.proto.MOUser.MNotify;
import com.zy.user.proto.MOUser.MNotifyList;

@Controller
@RequestMapping("/mobile/")
public class MUserController {
	
	@Autowired
	CouponService couponService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	StoreService storeService;
	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	StoreGoodsCategoryService storeGoodsCategoryService;
	@Autowired
	StoreCommentService storeCommentService;
	@Autowired
	UserCollectService userCollectService;
	@Autowired
	OrderService orderService;
	@Autowired
	StorePhotoService storePhoneService;
	@Autowired
	UserNotifyService userNotifyService;
	@Autowired
	NotifyService notifyService;
	@Autowired
	UserAddressService userAddressService;
	
	
	/**
	@api mMyCoupons mMyCoupons	//我的现金券
	@return MCouponList
	*/
	@RequestMapping("/mMyCoupons")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MCouponList.Builder mMyCoupons(MobileInfo mobileInfo) throws Exception {
		return userCouponService.getMyCoupons(mobileInfo.getUserid());
	}
	
	/**
	@api mAdaptCoupon mAdaptCoupon	//领取优惠券(登录)
	@return MCouponList
	*/
	@RequestMapping("/mAdaptCoupon")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MCouponList.Builder mAdaptCoupon(MobileInfo mobileInfo) throws Exception {
		return userCouponService.adaptCoupon(mobileInfo.getUserid());
	}
	
	/**
	@api mMyCollectStore mMyCollectStore	//我的收藏商家(分页 登录)
	@return MStoreMiniList
	*/
	@RequestMapping("/mMyCollectStore")
	@MobileMethod(isPage=true)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MStoreMiniList.Builder mMyCollectStore(MobileInfo mobileInfo,String lat,String lng,Integer page,Integer limit) throws Exception {
		return userCollectService.myCollectStore(mobileInfo.getUserid(), lat, lng, page, limit);
	}

	/**
	@api mMyCollectTg mMyCollectTg	//我的收藏团购(分页 登录)
	@return MTgGoodsMiniList
	*/
	@RequestMapping("/mMyCollectTg")
	@MobileMethod(isPage=true)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MTgGoodsMiniList.Builder mMyCollectTg(MobileInfo mobileInfo,String lat,String lng,Integer page,Integer limit) throws Exception {
		return userCollectService.myCollectGoods(mobileInfo.getUserid(), lat, lng, page, limit);
	}

	/**
	@api mOperCollect mOperCollect	//操作收藏
	@param optional string id  //收藏id
	@param optional number type  // 1 商品 2商家
	@param optional number oper  // 1 添加 2删除
	@return MRet //0成功
	*/
	@RequestMapping("/mOperCollect")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mOperCollect(MobileInfo mobileInfo,String id,Integer type,Integer oper) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		if(type==null) throw new MobException("type");
		//查找是否已收藏
		if(oper==1){
			int c= userCollectService.isCollect(mobileInfo.getUserid(), type, id);
			if(c>0) throw new MobException(MEnumError.HAS_COLLECT);
			UserCollect co = new UserCollect();
			co.setCreateTime(new Date());
			co.setFid(id);
			co.setType(type);
			co.setUid(mobileInfo.getUserid());
			co.setId(StringUtil.getUUID());
			userCollectService.save(co);
			
		}else{
			userCollectService.delByUserIdAndType(mobileInfo.getUserid(), type, id);
		}
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}
	
	
	
	/**
	@api mMyComment mMyComment	//我的评论(分页 登录)
	@return MMyCommentList
	*/
	@RequestMapping("/mMyComment")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MMyCommentList.Builder mMyComment(MobileInfo mobileInfo,Integer page,Integer limit) throws Exception {
		return storeCommentService.myComment(mobileInfo.getUserid(), page, limit);
	}
	
	
	
	/**
	@api mNotifyList mNotifyList	//我的消息(分页 登录)
	@param optional number type //类型 1系统通知
	@param optional number showType //显示类型 1:只显示标题 2:全部显示
	@return MNotifyList   
	*/
	@RequestMapping("/mNotifyList")
	@MobileMethod(isPage=true)
	public MNotifyList.Builder notifyList(MobileInfo mobileInfo,Integer type,Integer showType,Integer page,Integer limit) throws Exception {
		// 参数校验
		if (showType == null) {
			showType = 1;
		}
		if (type == null) {
			throw new MobException("type");
		}
		
		MNotifyList.Builder ret = MNotifyList.newBuilder();
		if(type == 1 && StringUtils.isNotBlank(mobileInfo.getUserid())){
			
			Page<UserNotify> list = userNotifyService.findByUserIdAndType(mobileInfo.getUserid(), type, new PageRequest(page, limit,new Sort(Direction.DESC, "createTime")));
			for (UserNotify notify : list) {
				MNotify.Builder n = MNotify.newBuilder();
				n.setId(notify.getId());
				n.setType(notify.getType());
				n.setTitle(StringUtil.emptyIfBlank(notify.getTitle()));
				n.setContent(showType == 1 ? "" : notify.getContent());
				n.setIsRead(notify.getIsRead());
				n.setCreateTime(DateUtil.getLnow(notify.getCreateTime()));
				n.setRedirectType(notify.getRedirectType());
				n.setRedirectContent(StringUtil.emptyIfBlank(notify.getRedirectContent()));
				ret.addNotify(n);
			}
			//设为已读
			userNotifyService.updateRead(mobileInfo.getUserid(), type);
		}else if(type == 2){
			Page<Notify> list = notifyService.findByStateAndUserIdIsNull(2, new PageRequest(page, limit,new Sort(Direction.DESC,"createTime")));
			
			for (Notify notify : list) {
				MNotify.Builder n = MNotify.newBuilder();
				n.setId(notify.getId());
				n.setTitle(StringUtil.emptyIfBlank(notify.getTitle()));
				n.setContent(showType == 1 ? "" : notify.getContent());
				n.setCreateTime(DateUtil.getLnow(notify.getCreateTime()));
				n.setRedirectType(notify.getRedirectType());
				n.setRedirectContent(StringUtil.emptyIfBlank(notify.getRedirectContent()));
				ret.addNotify(n);
			}
		}
		return ret;
	}
	
	/**
	 * 删除通知
	 * @param id 无则清空
	 * @param type //类型 1:系统通知
	 * @url /mobile?methodno=MDelNotify&debug=1&userid=&verify=&deviceid=&id=
	 */
	@RequestMapping("/mDelNotify")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder delNotify(MobileInfo mobileInfo,String id,Integer type) throws Exception {
		if (type == null) {
			throw new MobException("type");
		}
		//删除一条
		if(StringUtils.isNoneBlank(id)){
			userNotifyService.delete(id);
		}else{
			userNotifyService.deleteByUserIdAndType(mobileInfo.getUserid(), type);
		}
		
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}
	
	
	/**
	@api mReadNotify mReadNotify	//通知设为已读
	@param optional string id //通知id
	@return MRet  
	*/
	@RequestMapping("/mReadNotify")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder readNotify(MobileInfo mobileInfo,String id) throws Exception {
		if (StringUtils.isBlank(id)) {
			throw new MobException("id");
		}
		
		//设为已读
		userNotifyService.updateRead(id);
		
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}
	
	/**
	@api mNotify mNotify	//通知详情
	@param optional string id //通知id
	@return MNotify  
	*/
	@RequestMapping("/mNotify")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MNotify.Builder notify(MobileInfo mobileInfo,String id) throws Exception {
		if (StringUtils.isBlank(id)) {
			throw new MobException("id");
		}
		MNotify.Builder ret = MNotify.newBuilder();
		UserNotify notify = userNotifyService.findOne(id);
		if(notify!=null){
			ret.setId(notify.getId());
			ret.setTitle(StringUtil.emptyIfBlank(notify.getTitle()));
			ret.setContent(StringUtil.emptyIfBlank(notify.getContent()));
			ret.setIsRead(notify.getIsRead());
			ret.setCreateTime(DateUtil.asHtml(notify.getCreateTime()));
			ret.setRedirectType(notify.getRedirectType());
			ret.setRedirectContent(StringUtil.emptyIfBlank(notify.getRedirectContent()));
		}
		return ret;
	}
	
	/**
	@api mMyAddress mMyAddress	//我的地址(需要登录)
	@return MAddress
	*/
	@RequestMapping("/mMyAddress")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MAddress.Builder mMyAddress(MobileInfo mobileInfo) throws Exception {
		MAddress.Builder ret = MAddress.newBuilder();
		
		UserAddress address = userAddressService.selectMyAddress(mobileInfo.getUserid());
		
		if(address!=null){
			 ret.setAddress(address.getAddress());
			 ret.setArea(address.getArea());
			 ret.setId(address.getId());
			 ret.setName(address.getName());
			 ret.setPhone(address.getPhone());
			 ret.setZipCode(address.getZipCode());
		}
		return ret;
	}
	

	/**
	@api mEditAddress mEditAddress		//编辑地址(需要登录)
	@param required string area			//区域
	@param required string address		//详细地址
	@param required string phone		//联系方式
	@param required string name			//收件人
	@param required string zipCode		//邮编
	@param optional string id		//地址id
	@return MRet
	*/
	@RequestMapping("/mEditAddress")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mEditAddress(MobileInfo mobileInfo,String id,String name,String zipCode,String phone,String address,String area) throws Exception {
		MRet.Builder ret = MRet.newBuilder();
		
		UserAddress a = userAddressService.selectMyAddress(mobileInfo.getUserid());
		
		if(a!=null){
			a.setAddress(address);
			a.setArea(area);
			a.setName(name);
			a.setZipCode(zipCode);
			a.setPhone(phone);
			userAddressService.updateByPrimaryKeySelevtive(a);
		}else{
			a = new UserAddress();
			a.setId(StringUtil.getUUID());
			a.setAddress(address);
			a.setArea(area);
			a.setName(name);
			a.setZipCode(zipCode);
			a.setPhone(phone);
			a.setCreateTime(new Date());
			a.setUserId(mobileInfo.getUserid());
			a.setIsDefault(1);
			userAddressService.save(a);
		}
		return ret;
	}
	
	
}
